<template>
	<view class=""  style="margin-right: 10rpx;" :style="{'width':width}">

		 <yk-authpup ref="authPupYk" type="top" @changeAuth="authSuccess" :permissionID="permissionID"></yk-authpup>
		<!-- <view class="flex-row items-center group" @click="oncity"> -->
		<view class="flex-row items-center group" @click="onaddress">
	<!-- 	  <image v-if="type==1"
		    class="shrink-0 image_4"
		    src="https://qiniu.ccchongya.com/chongya/images/16947555487802052701.png"
		  />

		  <image v-else
		    class="shrink-0 image_4"
		    src="https://qiniu.ccchongya.com/chongya/images/16967453055641285259.png"
		  /> -->

		   <!-- <text  class="myicon myicon-weizhi t-color-y1"  :style="{'color':color}"></text> -->
		   <text  class="myicon myicon-weizhi "  :style="{'color':color}"></text>

		  <text class="font_2 text_2" :style="{'color':color}" style="width:100%;height:50rpx;line-height:50rpx;white-space: nowrap; overflow: hidden;text-overflow: ellipsis" >
		  {{addresstextshow}}
		  </text>

		</view>



		<!-- 	<popup-layer ref="popupRef" :direction="'right'">
				<view style="width:750upx;height: 100%;">
					<citySelect  v-if="currentAddressinfo.city"  @back_city="back_city"  :currentAddressinfo="currentAddressinfo"></citySelect>
				</view>
			</popup-layer> -->

			<popup-layer ref="popupAddress" :direction="'right'">
				<view style="width:750upx;height: 100%;">
					<get-address  @handleCurrentAddressinfo="handleAddressDataFromChild"  @back_address="back_address" @back_address_clear="back_address_clear" :hasPrmissionLocation="hasPrmissionLocation"  ></get-address>
				</view>
			</popup-layer>

	</view>
</template>

<script>

	const $ = require('@/utils/api.js');

	// #ifdef APP-PLUS
	// import waPermision from "@/js_sdk/wa-permission/permission.js"
	// #endif

	// import citySelect from '@/components/linzq-citySelect/linzq-citySelect.vue';
	import popupLayer from '@/components/popup-layer/popup-layer.vue';
	import getAddress from '@/components/getlocation/address.vue';
	export default {
		props: {

			type: {
				type: Number,
				default: 1
			},
			color: {
				type: String,
				default: '#000000'
			},
			width: {
				type: String,
				default: '200rpx'
			},
			autoLocation: {
				type: Boolean,
				default: true
			},
			// region: '请选择...',
			region: {
				type: String,
				default: '全国'
			},
			// //查询提示文字
			// placeholder: {
			// 	type: String,
			// 	default: '请输入城市名称'
			// },
			// //传入要排序的名称
			// formatName: {
			// 	type: String,
			// 	default: 'cityName'
			// },
			// //当前定位城市
			// activeCity: {
			// 	type: Object,
			// 	default: () => null
			// },
			// //热门城市
			// hotCity: {
			// 	type: Array,
			// 	default: () => []
			// },
			// //城市数据
			// obtainCitys: {
			// 	type: Array,
			// 	default: () => []
			// },
			// //是否有搜索
			// isSearch: {
			// 	type: Boolean,
			// 	default: true
			// }
		},

		watch: {
			obtainCitys(newData) {
				this.updateCitys(newData);
			},
			addresstext(val,oldVal) {
				
					console.log("watch addresstext ",val)
					
					
					
					let text =val;
					let startIndex = text.indexOf("省"); // 找到"start"的索引
					if (startIndex !== -1) {
						// 从"start"开始截取，直到字符串末尾
						let result = text.substring(startIndex+1);
						this.addresstextshow = result;
							console.log("return ",result)// 输出: "start with some text that we want to start with."
					} else {
						console.log("return 2",val)
						if(!val || val==[] ||  val==''||  val=='undefined'){
							this.addresstextshow="暂无获取地址信息"
						}else{
							this.addresstextshow = val;
						}
			
						// console.log("特定文字未找到");
					}
			}
			// region(newData){
			//     this.addresstext = newData
			//   }
		},
		components: {
			// citySelect,
			popupLayer,
			getAddress
		},
		computed: {},
		data() {
			return {
				hasPrmissionLocation:false,
				permissionID:'ACCESS_FINE_LOCATION',
				top: uni.getStorageSync('bartop') ? uni.getStorageSync('bartop') : 0,
				currentAddressinfo:{
				    latitude:"",
					longitude:"",
					address:"",
					region:"",
					city:"",
					citycode:"",
					district:"",
					province:"",
				},
				chooseAddressinfo:{
					latitude:"",
					longitude:"",
					address:"",
					region:"",
					city:"",
					citycode:"",
					district:"",
					province:"",
				},
				searchAddressinfo:{},
				statusBarHeight: this.statusBarHeight, //状态栏高度，在main.js里
				addresstext: '全国', //地区
				addresstextshow: '全国', //地区
				latitude:"",
				longitude :""
			}
	   	},
	    created() {
			this.init()
		},
		mounted() {
	 //    let text = '河南省安阳市文峰111区阳光小去101栋';
		
		// let startIndex = text.indexOf("省"); // 找到"start"的索引
		
		// if (startIndex !== -1) {
		//     // 从"start"开始截取，直到字符串末尾
		//     let result = text.substring(startIndex+1);
		//   		console.log("return ",result)// 输出: "start with some text that we want to start with."
		// } else {
		//     console.log("特定文字未找到");
		// }

		},
		onReady() {
			// this.init()
							// 实现
							//   1.首次进入app，检查本地存储，没有本地存储，就去发起权限申请，用户同意就手动调用获取位置的方法
							//   2.首次进入app，检查本地存储，没有本地存储，发起权限申请，用户点击拒绝，将拒绝时间存入本地，此时app没有获取定位权限
							//   3.再次进入app，检查本地存储，本地存储存在并且时间没有超过48小时，不调用权限申请，此时app没有获取定位权限
							//   4.再次进入app，检查本地存储，本地存储存超过48小时，删除本地存储，距离上次手动拒绝超过48小时，利用uniapp插件手动发起权限申请，重复第一步操作。实现功能！
				            //获取本地存储
							// let stor = uni.getStorageSync('expirationTime')
							// if (stor) {
				   //              //超过48小时，移除本地存储
							// 	if ((stor + (3600 * 24 * 2)) < Date.parse(new Date()) / 1000) { //过期了
							// 		uni.removeStorageSync('expirationTime')
							// 		console.log('存储过期了，调用权限');
				   //                  //插件方法，调起权限权限授权弹窗
				   //                 this.requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION')
							// 	    //这个是我自定义的权限使用说明弹窗
				   //                  this.$refs.popup.open('top')
							// 	} else {
				   //                  //没超过48小时，不做操作
							// 		console.log('存储没过期，我还不能调用权限');
							// 	}
							// } else {
							// 	console.log('没用检测到本地存储，调用权限');
							// 	this.requestAndroidPermission('android.permission.ACCESS_FINE_LOCATION')
							// 	this.$refs.popup.open('top')
							// }
		},
		methods: {
			handleAddressDataFromChild(receivedData){
				 console.log('Received from child:', receivedData);
				 this.currentAddressinfo = receivedData
				 this.init()

				 // this.addresstext="1111111111111"

				 // 	 console.log('Received from child  this.addresstext:',  this.addresstext);
			},
			init(){
				//获取存储的最近访问
				var that = this

				that.chooseAddressinfo  = uni.getStorageSync('chooseAddressinfo') || {};
				that.currentAddressinfo  = uni.getStorageSync('currentAddressinfo') || {};

				console.log("init	that.chooseAddressinfo  ",	that.chooseAddressinfo  )
				console.log("init	that.currentAddressinfo  ",	that.currentAddressinfo  )
				if(that.chooseAddressinfo.length == 0 || !that.chooseAddressinfo.address  ||  that.chooseAddressinfo =='undefined'  || !that.chooseAddressinfo    ){
						that.chooseAddressinfo = that.currentAddressinfo
						that.addresstext =  that.currentAddressinfo.address
				}
	
				that.addresstext =  that.chooseAddressinfo.address
				console.log("that.addresstext ",that.addresstext )
				if(	that.addresstext =="" ||  that.addresstext =="undefined"  ||  that.addresstext ==undefined){
						that.addresstext = "全国"
				}
				if(false){
					that.openAuthYk("ACCESS_FINE_LOCATION");
					return ;
				}
				that.addresstext = 	that.addresstext.replace(/.+?(省|市|自治区|自治州|县|区)/g,'')
				that.get()
			},
			// //这个是自己的方法名
			openAuthYk(permissionID){
				setTimeout(()=>{
				    this.permissionID = permissionID;
					this.$refs.authPupYk.open();
				},1000)
			},
			//权限获取后的回调函数
			authSuccess(permissionID){

				if(	permissionID =="ACCESS_FINE_LOCATION"){
										this.hasPrmissionLocation = true;
										this.get()
				}

			},
			updateLngLat(currentAddressinfo) {
					$.ajax({
						url: 'member/updateLngLat',
						data: {
							lng:currentAddressinfo.longitude,
							lat:currentAddressinfo.latitude
						},
						method: 'POST',
						success(res) {
						}
					})	
			},
			get(){
				console.log("get()get()get()get()get()" ,this.hasPrmissionLocation)
				var that = this
				console.log("that.mapfun.getlocation()",this.hasPrmissionLocation )
				// //#ifdef APP-PLUS
			 //      if(!that.hasPrmissionLocatio){
				// 	  	that.openAuthYk("ACCESS_FINE_LOCATION")
				// 		return;
				// }
				// //#endif
				
				
					
								  					that.mapfun.getlocation().then(data => {
														
														
															console.log("that.mapfun.getlocation()",data )
								  									that.mapfun.getCityinfo().then(res => {
								  									
								  											// that.regiontext =  res.addressComponent.province+res.addressComponent.city

																		console.log('getCityinfo',res)


								  											    that.city = res.addressComponent.city;
								  												// that.currentname = `${data[0].desc}`
								  												that.currentaddress = res.formatted_address
								  												let longitude =  uni.getStorageSync('longitude');
								  												let latitude = uni.getStorageSync('latitude');

																		console.log('getCityinfo longitude start位置信息',longitude)
																			console.log('getCityinfo latitude start位置信息',latitude)
																				
								  												that.currentlat = longitude // 当前位置纬度
								  												that.currentlng = latitude // 当前位置经度



								  												that.currentdistancec = that.mapfun.getDistance(that.currentlat, that.currentlng, that.currentlat, that.currentlng, ) // 当前位置经度

								  												that.currentAddressinfo.latitude = latitude
								  												that.currentAddressinfo.longitude = longitude
								  												that.currentAddressinfo.address = that.currentaddress
								  												that.currentAddressinfo.region = that.regiontext

								  												that.currentAddressinfo.city = that.city
																				that.currentAddressinfo.citycode = res.addressComponent.citycode;
																				that.currentAddressinfo.district = res.addressComponent.district;
																				that.currentAddressinfo.province = res.addressComponent.province;
																				that.currentAddressinfo.country = res.addressComponent.country;



								  								                that.addresstext = that.currentAddressinfo.address
								  													console.log('getCityinfo addresstext', that.addresstext)
																					
																					
																					uni.setStorageSync('currentAddressinfo',that.currentAddressinfo);
																				
																				
																					console.log("00000self.currentAddressinfo",self.currentAddressinfo)
																				if(!that.chooseAddressinfo){
																					that.chooseAddressinfo =  that.currentAddressinfo
																					uni.setStorageSync('chooseAddressinfo',that.chooseAddressinfo);
																				}
																				
															
																				that.updateLngLat(that.currentAddressinfo)

								  									}).catch(err => {
								  										console.log(222222222,err)
								  											that.currentname = "暂无当前位置信息"
								  									})
							}).catch(err => {
								console.log("0000000000",err)
							})


			},

			oncity() {
				var that = this

				// if(this.autoLocation){
				// 	uni.navigateTo({
				// 		url: `/pages/a`
				// 	});
				// }else{
					this.$refs.popupRef.show();

				// }

			},

			onaddress() {

				var that = this

				this.$refs.popupAddress.show();
			},
			addressClose(){
				this.$refs.popupAddress.close();
			},
			back_address_clear(){
					this.$refs.popupAddress.close();
			},
			back_address(e) {
				var that = this

			// 	console.log("back_address")


				console.log("eeeeeeeeee",e)

				that.chooseAddressinfo = e

				uni.setStorageSync('chooseAddressinfo',that.chooseAddressinfo);
			// 	uni.setStorageSync('chooseAddressinfo',e);


			    that.addresstext =  that.chooseAddressinfo.addresss

			// 	that.longitude =  e.location.split(',')[0] // 当前位置纬度
			// 	that.latitude =  e.location.split(',')[1] // 当前位置经度
				if (e !== 'no') {
					this.addresstext =  that.chooseAddressinfo.address
			// 		// console.log('this.regiontext',this.regiontext)
				    uni.$emit('chooseAddressinfo', that.chooseAddressinfo)
					that.updateLngLat(that.chooseAddressinfo)
					
					uni.$emit('region', this.addresstext)
					that.$refs.popupAddress.close();
				} else {
					that.$refs.popupAddress.close();
				}
			},
			back_city(e) {
				if (e !== 'no') {
					this.addresstext = e.address
					console.log('this.addresstext',this.addresstext)
					uni.$emit('region', e.address)
					this.$refs.popupRef.close();
				} else {
					this.$refs.popupRef.close();
				}
			}
		}
	};
</script>

<style scoped>
	.height {
		height: var(--status-bar-height);
	}

	.group {
	  padding-left: 0rpx;
	}
	.image_4 {
	  width: 38rpx;
	  height: 38rpx;
	}
	.font_2 {
	  /* font-size: 24rpx; */
	  font-family: HarmonyOSSansSC;
	  line-height: 22rpx;
	  color: #666e7a;
	}
	.text_2 {
	  margin-left: 8rpx;
	  /* color: #ffffff; */
	}

</style>
